package org.opensource.extfaces.tags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.el.ELException;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;

import com.sun.facelets.FaceletContext;
import com.sun.facelets.FaceletException;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagConfig;
import com.sun.facelets.tag.TagHandler;

public class ButtonTag extends TagHandler {
	private Map<String, Object> map = null;

	public ButtonTag(TagConfig config) {
		super(config);
		map = new HashMap<String, Object>();
	}

	public void apply(FaceletContext ctx, UIComponent parent)
			throws IOException, FacesException, FaceletException, ELException {
		// TODO Auto-generated method stub
		List<Map<String, Object>> fields = getButtons(ctx);
		TagAttribute[] attributes = this.tag.getAttributes().getAll();
		for (int i = 0; i < attributes.length; i++) {
			TagAttribute attribute = attributes[i];
			String name = attribute.getLocalName();
			Object value = attribute.getValue();
			map.put(name, value);
		}

		fields.add(map);
		this.nextHandler.apply(ctx, parent);
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> getButtons(FaceletContext ctx) {
		List<Map<String, Object>> buttons = (List) ctx.getAttribute("buttons");
		if (buttons == null) {
			buttons = new ArrayList<Map<String, Object>>();
			ctx.setAttribute("buttons", buttons);
		}

		return buttons;
	}

}
